#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import json
import aiohttp_jinja2
from aiohttp import web

import db
import blogutils
from coreweb import query_string, post_params

routes = web.RouteTableDef()
module_name = 'blog'


@routes.get('/%s' % module_name)
async def blogs(request):
    params = query_string(request)
    index = params.get('index', 1)
    size = params.get('size', 5)
    page = {'index': index, 'size': size}
    path = params.get('path', '/root')
    # mode = params.get('mode', 'list')
    data = blogutils.getblogs(page, path)
    data = dict(data, **request.app['view_commons'])
    data['mode'] = 'list'
    return {'data': data, '__template__': 'blog.html'}


@routes.get('/%s/edit' % module_name)
async def edit(request):
    params = query_string(request)
    id = params.get('id', None)
    path = params.get('path', '/root')
    data = {}
    data = dict(data, **request.app['view_commons'])
    blog = None
    if id is not None:
        result = blogutils.get_blog(id)
        if result['status']:
            blog = result['msg']
        else:
            logging.error('[ERROR]get blog: %s' % result['msg'])
    if blog is None:
        blog = db.Blog()
    data['blog'] = blog
    data['mode'] = 'edit'
    data['path'] = path[1:].split('/')
    return {'data': data, '__template__': 'blog.html'}


@routes.post('/%s/edit' % module_name)
async def save(request):
    params = await request.json()
    name = params.get('name', None)
    summary = params.get('summary', None)
    content = params.get('content', None)
    id = params.get('id', None)
    path = params.get('path', '/root')
    if content is None or len(content) <= 0:
        return {'code': -1, 'msg': 'content [%s]: %s' % (params, content)}
    if name is None or len(name) <= 0:
        return {'code': -1, 'msg': 'name [%s]: %s' % (params, name)}
    if summary is None or len(summary) <= 0:
        return {'code': -1, 'msg': 'summary [%s]: %s' % (params, summary)}
    data = {'content': content, 'name': name,
            'summary': summary, 'path': path, 'id': id}
    result = blogutils.save_blog(data, None)
    if result['status']:
        return {'code': 0, 'msg': result['msg']}
    logging.error('failed to save[%s]: %s' % (path, result))
    return {'code': -1, 'msg': 'failed to save[%s]: %s' % (path, result['msg'])}


@routes.get('/%s/view' % module_name)
async def view(request):
    params = query_string(request)
    id = params.get('id', None)
    path = params.get('path', '/root')
    data = {}
    data = dict(data, **request.app['view_commons'])
    blog = None
    if id is not None:
        result = blogutils.get_blog(id)
        if result['status']:
            blog = result['msg']
        else:
            logging.error('[ERROR]get blog: %s' % result['msg'])
    if blog is None:
        blog = db.Blog()
    data['blog'] = blog
    data['mode'] = 'view'
    data['path'] = path[1:].split('/')
    return {'data': data, '__template__': 'blog.html'}


@routes.get('/%s/mkdir/{name}' % module_name)
async def mkdir(request):
    name = request.match_info['name']
    params = query_string(request)
    parent = params['parent']
    result = blogutils.makedir(parent, name)
    if result['status']:
        return web.json_response({'code': 0, 'msg': parent})
    logging.error('failed to makedir(%s, %s): %s' %
                  (parent, name, result['msg']))
    return web.json_response({'code': -1, 'msg': 'failed to makedir(%s, %s): %s' % (parent, name, result['msg'])})


@routes.get('/%s/delete/{id}' % module_name)
async def delete(request):
    id = request.match_info['id']
    params = query_string(request)
    result = blogutils.delete(id)
    if result['status']:
        return web.json_response({'code': 0, 'msg': result['msg']})
    logging.error('failed to delete(%s): %s' % (id, result['msg']))
    return web.json_response({'code': -1, 'msg': 'failed to delete(%s): %s' % (id, result['msg'])})
